<?php
require_once('base_controller.php');

class user_controller extends base_controller
{

    public function dowork()
    {
        $msg_response = new message(WARNING_query_failed, 0, STR_text);
        
        try
        {
            switch ($this->method)
            {
                case 'get_currentuser':
                    {
                        $id_my = $this->current_id;
                        $user = self::get_user($id_my);
                
                        $msg_response = new message($user, 1, STR_object); //json_encode
                    }
                    break;
                    
                case 'get_user':
                    {
                        if(!isset($this->parameters['id']))
                            throw new Exception(warning_parameter_needed('id')); //
                        
                        $id_toget = addslashes(trim($this->parameters['id']));
                        $id_my = $this->current_id;
                        
                        //若不是本人，需判断是否为好友，是否有权限访问信息
                        if($id_my != $id_toget && !friendship_controller::is_friend($id_my, $id_toget))
                        {
                            $msg_response = new message("The user is not your friend. ", 0, STR_text);
                        }
                        else
                        {
                            $user = self::get_user($id_toget);
                            $msg_response = new message($user, 1, STR_object);
                        }                        
                    }
                    break;
                
                //获取所有用户信息列表
                case 'userslist':
                    {
                        $id_my = $this->current_id;
                        $users = self::get_userslist($id_my);
                        
                        $msg_response = new message($users, 1, STR_array); //json_encode
                    }
                    break;
            
                case 'search_nickname':             //查询nickname, 结果仅包含匹配的id和nickname
                    {
                        if(!isset($this->parameters['nickname']))
                            throw new Exception(warning_parameter_needed('nickname')); //
            
                        $nickname = addslashes(trim($this->parameters['nickname'])); 
                        
                        $users = self::search_nickname($nickname);
            
                        $msg_response = new message($users, 1, STR_array);     
                    }
                    break;
                                
                case 'search_nickname_for_friend':   //查询nickname以添加好友, 结果将包含是否为朋友关系
                    {
                        if(!isset($this->parameters['nickname']))
                            throw new Exception(warning_parameter_needed('nickname')); //
            
                        $nickname = addslashes(trim($this->parameters['nickname'])); 
                        $id_my = $this->current_id;
                        $users = self::search_nickname_for_friend($nickname, $id_my);
                              
                        $msg_response = new message($users, 1, STR_array);                             
                    }
                    break;
            
                default:
                    {
                        $msg_response->content = warning_parameter_invalid('method', $this->method);
                    }
                    break;
            
            }
        } 
        catch (Exception $e) 
        {
            $msg_response->content = $e->getMessage();
        }        
        
        return $msg_response;
    }
    
    
    
    public static function get_userslist($id_my)
    {
        $db = db_connect();
        
        $str_query = //"select id from users"; //id
            "select users.id , users.nickname ,
                case when users.id in
                (
                    select useraccept as friends from friendship where userask = '".$id_my."'
                    union 
                    select userask as friends from friendship where useraccept = '".$id_my."'
                ) then 1 else 0 end
                as isfriend
            from users
            where users.id <> '".$id_my."'
            ";
        $result = $db->query($str_query);
                
        db_is_result_succeed($result, $db);
        
        $users = dbresult_to_objects_array($result);
        //$users = dbresult_to_rows_array($result);
        
        return $users;
    }
    
    /**
     * 注册新用户。若注册成功，返回true；若失败，会抛出Exception。
     * (待结合get_user()函数使用)
     * @param unknown $id
     * @param unknown $nickname
     * @param unknown $passwd
     * @param unknown $email
     * @throws Exception
     * @return boolean
     */
    public static function register_newuser($id, $nickname, $passwd, $email)
    {        
        $dbconn= db_connect();
                
        $timesignup = date("Y-m-d H:i:s");
        
        $strquery = "select * from users where id = '".$id."'";
        
        $result = $dbconn->query($strquery);
        
        if(!$result)
            throw new Exception(WARNING_query_failed);
        
        if($result->num_rows>0)
            throw new Exception('The Wechat id: '.$id.' is taken. Please go back and choose another one'); 

        $strquery= "insert into users (id, nickname, passwd, email, timesignup) values ('".$id."', '".$nickname."', sha1('".$passwd."'), '".$email."', '".$timesignup."');" ;  // 

        $result = $dbconn->query($strquery);
        
        if(!$result)
            throw new Exception('Register failed. Unknow failure... ');
                
        return true;
    }
    
    /**
     * (待结合get_user()函数使用)
     * @param unknown $id
     * @param unknown $passwd
     * @param unknown $do_passwd_hash 是否在判断前给密码计算散列值，否，则认为传入的密码已经过散列处理；散列算法为sha1
     * @throws Exception
     * @return boolean
     */
    public static function login($id, $passwd, $do_passwd_hash)
    {
        $dbconn = db_connect();
        
        if($do_passwd_hash)
        {
            $passwd = sha1($passwd);
        }
                
        //第一行查询只查找id是否存在；第二行查询id与passwd是否匹配
        $strquery = "select count(*) from users where id = '".$id."' union ALL ".
            "select count(*) from users where id = '". $id."' and passwd = '".$passwd."'";
        
        $result = $dbconn->query($strquery);

        if(!$result || $result->num_rows != 2)
            throw new Exception(WARNING_query_failed);
        
        if($result->fetch_row()[0] < 1)
            throw new Exception(WARNING_id_notexist);
        
        if($result->fetch_row()[0] < 1)
            throw new Exception(WARNING_passwd_incorrect);
                
        //return true;
        return self::get_user($id);
    }
    


    /**
     * 基于Session检查当前用户是否为已登录用户
     * @return unknown|NULL 若已登录，返回用户id；否，则返回false
     */
    public static function get_userid()
    {
        if(isset($_SESSION[STR_valid_user]))
        {
            return $_SESSION[STR_valid_user];
        }
        else
        {
            return false;
        }
    }
    
    public static function is_current_user($id)
    {
        return self::get_userid() === $id;
    }
    
    public static function is_current_user_throw($id)
    {
        if(self::is_current_user($id))
            return true;
        else
            throw new Exception(WARNING_unauthorized);
    }
    
    

    /**
     * 根据用户id从数据库中读取用户信息
     * @param unknown $id
     * @throws Exception
     * @return object 返回对象形式的用户信息
     */
    public static function get_user($id_toget)
    {
        $db = db_connect();
    
        $str_query = "select id,nickname,email from users where id = '".$id_toget."' "; 
        
        $result = $db->query($str_query);
            
        db_is_result_succeed($result, $db);
    
        if($result->num_rows <1)
            throw new Exception(warning_id_notexist($id_toget));
    
        //return $result->fetch_row();
        return $result->fetch_object();
    }
    
    public static function search_nickname($nickname)
    {
        $db=db_connect();
        
        $str_query = "select id,nickname from users where nickname like '%".$nickname."%'";
        
        $result = $db->query($str_query);

        db_is_result_succeed($result, $db);
        
        $users = dbresult_to_objects_array($result);
        
        return $users;
    }
    
    /**
     * 根据$nickname和$id_my查询用户信息，查询结果主要用于添加好友操作
     * @param unknown $nickname 查询用户的nickname模式，数据库查询时基于“%nickname%”模式
     * @param unknown $id_my 执行查询操作的用户的id，通常为当前用户；使用此id主要用于判断结果得到的各用户是否与该id用户为朋友关系（即结果中的isfriend属性值）
     * @throws Exception
     * @return Ambigous <NULL, unknown> 返回的用户信息为对象数组形式，各对象中包含了id,nickname,isfriend三个属性，其中isfriend属性值为“1”或“0”；由于$id数组中不包含$id_my用户
     */
    public static function search_nickname_for_friend($nickname, $id_my)
    {
        $db=db_connect();
        
        $str_query = //"select id,nickname from users where nickname like '%".$nickname."%'";
            "select users.id , users.nickname , 
                case when users.id in 
                (
                    select useraccept as friends from friendship where userask = '".$id_my."'
                    union
                    select userask as friends from friendship where useraccept = '".$id_my."'
                ) then 1 else 0 end 
                as isfriend
            from users
            where users.nickname like '%".$nickname."%' and users.id <> '".$id_my."'
            ";
        
        $result = $db->query($str_query);

        db_is_result_succeed($result, $db);
    
        $users = dbresult_to_objects_array($result);
    
        return $users;
    }
    
    //public static function se
    
    
    
    
    
    
    
    
    
    
    
    
    
    
}


?>